package com.tusuo.stds.ui.main;

import android.content.Intent;
import android.content.SharedPreferences;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.tusuo.stds.MyApp;
import com.tusuo.stds.R;
import com.tusuo.stds.biz.CurrentUser;
import com.tusuo.stds.biz.PageStatus;
import com.tusuo.stds.di.DaggerScope;
import com.tusuo.stds.di.Injector;
import com.tusuo.stds.rest.ApiHelper;
import com.tusuo.stds.rest.UserInfo;
import com.tusuo.stds.ui.BaseToolbarFragment;
import com.tusuo.stds.ui.account.AccountActivity_;
import com.tusuo.stds.ui.lab.LabActivity_;
import com.tusuo.stds.ui.level.LevelRecordActivity_;
import com.tusuo.stds.ui.settings.SettingsActivity_;
import com.tusuo.stds.util.Utils;
import com.tusuo.stds.ui.vip.VipActivity_;

import org.androidannotations.annotations.AfterInject;
import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Background;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EFragment;
import org.androidannotations.annotations.ViewById;
import org.androidannotations.annotations.res.StringRes;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import javax.inject.Inject;

import autodagger.AutoComponent;
import autodagger.AutoInjector;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import rx.Subscriber;
import timber.log.Timber;

import static com.tusuo.stds.Constants.AVATAR_FILE;

/**
 * @author J.Huang
 * @version 1.1
 *
 */
@AutoComponent(
        dependencies = MyApp.class
)
@AutoInjector
@DaggerScope(MeFragment.class)
@EFragment(R.layout.frag_me)
public class MeFragment extends BaseToolbarFragment {

    @Inject
    ApiHelper mApiHelper;
    @Inject
    SharedPreferences mSharedPref;
    @Inject
    CurrentUser mCurrentUser;

    @ViewById(R.id.me_iv_avatar)
    ImageView ivAvatar;
    @ViewById(R.id.me_tv_name)
    TextView tvName;
    @ViewById(R.id.me_iv_vip)
    ImageView ivVip;

    @StringRes(R.string.toolbar_title_me)
    String toolbarTitle;
    @StringRes(R.string.err_msg_server)
    String mErrMsgServer;
    @StringRes(R.string.err_msg_fetching_data)
    String mErrMsgFetchingData;

    private UserInfo mUserInfo = null;
    private String mMobileNum = "";
    private boolean mSimilarityState = false;

    private Subscriber<UserInfo> mGetUserInfoSubscriber = null;


    @AfterInject
    void initDI() {
        Injector.initMeFragmentComponent().inject(this);
    }

    @AfterViews
    void initData() {
        PageStatus pageStatus = new PageStatus(true, false, toolbarTitle);
        initData(pageStatus,null);
    }

    @Override
    public void onStart() {
        super.onStart();
        mGetUserInfoSubscriber = new GetUserInfoSubscriber();
        mApiHelper.getUserInfo(mGetUserInfoSubscriber);
    }

    /*@Override
    public void onResume() {
        super.onResume();

        mGetUserInfoSubscriber = new GetUserInfoSubscriber();
        mApiHelper.getUserInfo(mGetUserInfoSubscriber);
    }*/

    @Override
    public void onPause() {
        if (mGetUserInfoSubscriber != null) {
            mGetUserInfoSubscriber.unsubscribe();
            mGetUserInfoSubscriber = null;
        }

        super.onPause();
    }

    @Override
    protected void findViews() {
        mToolbar = (Toolbar) getActivity().findViewById(R.id.me_toolbar);
        mToolbarTitle = (TextView) getActivity().findViewById(R.id.me_tv_toolbar_title);
    }

    @Click({R.id.me_layout_account})
    void setAccount() {
        if (Utils.UI.isFastDoubleClick()) {
            return;
        }

        if (mUserInfo != null) {
            Intent intent = new Intent();
            intent.setClass(getActivity(), AccountActivity_.class);
            startActivity(intent);
        } else {
            Utils.UI.showToastShort(mErrMsgFetchingData);
        }
    }

    @Click(R.id.me_laytou_vip)
    void toVipPage() {
        if (Utils.UI.isFastDoubleClick()) {
            return;
        }

        if (mUserInfo != null) {
            Intent intent = new Intent();
            intent.setClass(getActivity(), VipActivity_.class);
            startActivity(intent);
        } else {
            Utils.UI.showToastShort(mErrMsgFetchingData);
        }

    }

    @Click(R.id.me_layout_history)
    void toHistory() {
        if (Utils.UI.isFastDoubleClick()) {
            return;
        }

        Intent intent = new Intent();
        intent.setClass(getActivity(), LevelRecordActivity_.class);
        startActivity(intent);
    }

    @Click(R.id.me_layout_lab)
    void setLab() {
        if (Utils.UI.isFastDoubleClick()) {
            return;
        }

        Intent intent = new Intent();
        intent.setClass(getActivity(), LabActivity_.class);
        intent.putExtra("similarityState", String.valueOf(mSimilarityState));
        startActivity(intent);
    }

    @Click(R.id.me_layout_settings)
    void setSettings() {
        if (Utils.UI.isFastDoubleClick()) {
            return;
        }

        Intent intent = new Intent();
        intent.setClass(getActivity(), SettingsActivity_.class);
        intent.putExtra("mobileNum", mMobileNum);
        startActivity(intent);
    }

    @Background
    void downloadImg(String imgUrl) {
        if (TextUtils.isEmpty(imgUrl)) {
            return;
        }

        imgUrl = Utils.getCorrectImageUrl(imgUrl);

        OkHttpClient httpClient = new OkHttpClient();

        Request request = new Request.Builder().url(imgUrl).build();

        InputStream is = null;
        FileOutputStream fos = null;
        try {
            Response response = httpClient.newCall(request).execute();
            if (response.isSuccessful()) {
                byte[] buf = new byte[2048];
                int len = 0;
                is = response.body().byteStream();
                File file = new File(AVATAR_FILE);
                fos = new FileOutputStream(file);
                while ((len = is.read(buf)) != -1) {
                    fos.write(buf, 0, len);
                }
                fos.flush();
            } else {
                Utils.UI.showToastShort("网络不可用！请检查网络设置后重启应用");
            }
        } catch (IOException e1) {
            e1.printStackTrace();
        } finally {
            try {
                if (is != null) {
                    is.close();
                }
                if (fos != null) {
                    fos.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    }

    private class GetUserInfoSubscriber extends Subscriber<UserInfo> {
        @Override
        public void onCompleted() {}

        @Override
        public void onError(Throwable e) {
            Timber.d(e.toString());
            Utils.UI.showToastShort(mErrMsgServer);
        }

        @Override
        public void onNext(final UserInfo userInfo) {
            if (userInfo.checkState(getContext())) {
                mUserInfo = userInfo;

                if (!TextUtils.isEmpty(userInfo.Photo)) {
                    String imgUrl = Utils.getCorrectImageUrl(userInfo.Photo);

                    Glide
                            .with(getContext())
                            .load(imgUrl)
                            .centerCrop()
                            .into(ivAvatar);

                } else {
                    Glide
                            .with(getContext())
                            .load(R.drawable.img_avatar_default)
                            .centerCrop()
                            .into(ivAvatar);
                }

                if (!TextUtils.isEmpty(userInfo.Name)) {
                    tvName.setText(Utils.Text.getTruncatedString(userInfo.Name, 16));
                } else {
                    tvName.setText("请设置名字");
                }

                if (userInfo.VipLevel == 0) {
                    ivVip.setBackgroundResource(R.drawable.st_my_icon_vip01);
                }else {
                    ivVip.setBackgroundResource(R.drawable.st_my_icon_vip02);
                }

                mMobileNum = userInfo.MobilePhone;
                mSimilarityState = userInfo.IsOpenSimilarity;
                mCurrentUser.setOpenSimilarityState(mSimilarityState);
            }
        }
    }
}
